package myJs.common

import com.softwaremill.quicklens._
import myJs.Implicits._
import myJs.api.Api
import myJs.common.loadSample.LoadSample
import myJs.cps.Style
import myJs.myPkg.reactHookForm.{RegisterOptions, UseFormRT, ValidationValueMessage}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Sample.{SampleInfo, TestData}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Fragment
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._

import scala.collection.immutable.SeqMap
import scala.scalajs.js.|


/**
 * Created by yz on 21/1/2022
 */
@react object TestInfoCp {

  case class Props(
                    useForm: UseFormRT,
                    sampleInfo: SampleInfo,
                    sampleInfoChange: SampleInfo => Unit
                  )

  val component = FunctionalComponent[Props] { props =>

    val (hasRefreshCompanyMap, setHasRefreshCompanyMap) = useState(false)
    val (companyMap, setCompanyMap) = useState(SeqMap[String, String]())

    object FTool {

      def testTypeChange(curI: Int) = (v: String) => {
        val curSampleInfo = props.sampleInfo.modify(_.tests).using { testInfo =>
          testInfo.modify(_.index(curI)).using { testData =>
            testData.modify(_.testType).setTo(v)
          }
        }
        props.sampleInfoChange(curSampleInfo)
      }

      def companyChange(curI: Int) = (v: String) => {
        val curSampleInfo = props.sampleInfo.modify(_.tests).using { testInfo =>
          testInfo.modify(_.index(curI)).using { testData =>
            testData.modify(_.company).setTo(v)
          }
        }
        props.sampleInfoChange(curSampleInfo)
      }

      def refreshCompanyMap = {
        Api.companyMember.allCompany.map { companys =>
          val curCompanyMap = companys.optionMap
          setCompanyMap(curCompanyMap)
          setHasRefreshCompanyMap(true)
        }
      }

      def addTest = () => {
        val curSampleInfo = props.sampleInfo.modify(_.tests).using { testInfo =>
          testInfo :+ TestData()
        }
        props.sampleInfoChange(curSampleInfo)
      }

      def deleteTest(curI: Int) = () => {
        val curSampleInfo = props.sampleInfo.modify(_.tests).using { testInfo =>
          testInfo.removedByI(curI)
        }
        props.sampleInfoChange(curSampleInfo)
      }

    }

    useEffect(() => {
      FTool.refreshCompanyMap
    }, List()
    )

    useEffect(() => {
      props.useForm.trigger()
    }, List(props.sampleInfo.tests)
    )

    Fragment(
      props.sampleInfo.tests.zipWithIndex.map { case (testData, curI) =>
        val testTypeName = s"testType${curI}"
        val companyName = s"company${curI}"
        val fieldNames = List(testTypeName, companyName)
        val noValid = fieldNames.exists(props.useForm.formState.errors.isDefinedAt(_))
        val hasErrorCls = if (noValid) "has-error" else ""
        div(key := s"${curI}",

          div(className := s"form-group ${hasErrorCls}",
            label(className := "control-label col-sm-2", "测试类型:"),
            div(className := "col-sm-3",
              PureInputCp(useForm = props.useForm, name = s"${testTypeName}", value = testData.testType,
                onChange = FTool.testTypeChange(curI),
                registerOptions = {
                  val info = "测试类型"
                  RegisterOptions(
                    required = ValidationValueMessage(value = true, message = s"${info}不能为空！"),
                  )
                }
              )
            ),
            label(className := "control-label col-sm-2", "公司:"),
            div(className := "col-sm-3", style := Style(),
              if (hasRefreshCompanyMap) {
                PureRSelectCp(useForm = props.useForm, value = testData.company, onChange = FTool.companyChange(curI),
                  optionMap = companyMap, name = s"${companyName}",
                  registerOptions = {
                    val info = "公司"
                    RegisterOptions(
                      required = ValidationValueMessage(value = true, message = s"${info}不能为空！"),
                    )
                  }
                )
              } else null
            ),
            div(className := "col-sm-2",
              button(`type` := "button", className := "btn btn-default", onClick := FTool.deleteTest(curI),
                span(className := "fa fa-trash", " 删除此测试"),
              ),
            )

          ),

        )

      },
      div(className := "form-group",
        div(className := "actions col-sm-offset-2 col-sm-6",
          button(`type` := "button", className := "btn btn-default", onClick := FTool.addTest,
            span(className := "fa fa-plus", s" 新增测试")
          ),
        )
      ),
    )

  }


}
